<template>
	<view class="container">
		<!-- VIP提示 -->
		<!-- <view v-if="!isVip" class="vip-banner" @tap="showVipModal"> -->
		<view v-if="!isVip" class="vip-banner">
			<view class="vip-info">
				<text class="vip-title">开通会员享专业配音</text>
				<text class="vip-desc">无限次使用、多种专业音色、无广告</text>
			</view>
			<!-- <button class="vip-btn" open-type="contact">立即开通</button> -->
			<button class="vip-btn" @tap="sendMessage" open-type="contact">联系客服</button>
		</view>

		<!-- 输入区域 -->
		<view class="input-area">
			<view class="input-header">
				<!-- <text 
					class="input-tab" 
					:class="{ active: inputMode === 'import' }"
					@tap="switchInputMode('import')"
				>导入文案</text> -->
				<text 
					class="input-tab" 
					:class="{ active: inputMode === 'paste' }"
					@tap="switchInputMode('paste')"
				>粘贴文案</text>
				<text class="hot-sample" @tap="showSampleModal">🔥配音样例</text>
			</view>
			<textarea
				v-model="inputText"
				class="input-content"
				placeholder="这里输入或粘贴要配音的文字 温馨提示：1. 规范使用标点符号，配音更准确。如使用，。断句 2. 如有多音字发音不对，可输入发音相同的字替代"
				:maxlength="configData.vip_user_limits.max_chars_per_request"
			/>
			<view class="word-count">{{ inputText.length }}/{{ configData.vip_user_limits.max_chars_per_request }}</view>
			
			<!-- 工具按钮 -->
			<view class="tool-buttons">
				<!-- <button class="tool-btn">停顿调节</button> -->
				<!-- <button class="tool-btn">发音纠正</button> -->
				<!-- <button class="tool-btn">查敏感词</button> -->
				<button class="tool-btn" @tap="clearText">清除文字</button>
			</view>
		</view>

		<!-- 语音设置 -->
		<view class="voice-settings">
			<view class="setting-item" @tap="showVoiceModal">
				<view class="setting-label">
					<text class="icon">🔊</text>
					<text>声音</text>
				</view>
				<view class="setting-value">
					{{ selectedVoice.name }}
					<text class="tag">{{ selectedVoice.tag }}</text>
				</view>
				<tts-icons type="youbianjiantou" size="30" color="#ddd" />
			</view>

			<view class="setting-item" @tap="showSpeedModal">
				<view class="setting-label">
					<text class="icon">⏱️</text>
					<text>语速</text>
				</view>
				<view class="setting-value">{{ speedLabel }}</view>
				<tts-icons type="youbianjiantou" size="30" color="#ddd" />
			</view>

			<view class="setting-item" @tap="showEmotionModal">
				<view class="setting-label">
					<text class="icon">😊</text>
					<text>情感强度</text>
				</view>
				<view class="setting-value">{{ emotionLabel }}</view>
				<tts-icons type="youbianjiantou" size="30" color="#ddd" />
			</view>
			<view class="setting-item" @tap="gotoHistory">
				<view class="setting-label">
					<text class="icon">📝</text>
					<text>配音历史</text>
				</view>
				<tts-icons type="youbianjiantou" size="30" color="#ddd" />
			</view>
			<!-- 客服按钮 -->
			<button class="feature-list-item customer-service-btn" @tap="sendMessage" open-type="contact">
				<view class="feature-list-item-content">
					<tts-icons type="kefu" size="25" color="#07c160" />
					<text style="margin-left: 10rpx;font-size: 28rpx;" class="feature-name">联系客服</text>
				</view>
				
				<tts-icons type="youbianjiantou" size="30" color="#ddd" />
			</button>
		</view>

		<!-- 广告位 -->
		<!-- <view v-if="showAd" class="ad-container">
			<ad :unit-id="AD_CONFIG.BANNER.adUnitId"></ad>
		</view> -->

		<!-- 底部按钮 -->
		<view class="bottom-buttons">
			<button class="primary-btn" :loading="isConverting" @tap="handleConvert">
				{{ isConverting ? '合成中 ' + progress + '%' : '合成配音' }}
			</button>
			<button class="secondary-btn" :disabled="!audioUrl" @tap="handleExport">导出配音</button>
			<button v-if="audioUrl" class="play-btn" @tap="handlePlay">
				{{ isPlaying ? '停止播放' : '播放配音' }}
			</button>
		</view>

		<!-- VIP弹窗 -->
		<VipModal 
			v-model:show="showVipModalFlag"
			@buy="handleBuyVip"
		/>

		<!-- 音色选择弹窗 -->
		<view v-if="showVoiceModalFlag" class="modal-overlay" @tap="closeVoiceModal">
			<view class="voice-modal" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">选择音色</text>
					<text class="close-btn" @tap="closeVoiceModal">×</text>
				</view>
				<view class="voice-content">
					<!-- 分类选择区域 -->
					<view class="category-container">
						<!-- 左侧分类列表 -->
						<scroll-view scroll-y class="category-list">
							<view 
								v-for="(category, index) in voiceCategories" 
								:key="category.id"
								class="category-item"
								:class="{ active: currentCategoryIndex === index }"
								@tap="selectCategory(index)"
							>
								<text class="category-name">{{ category.category }}</text>
								<text class="category-count">{{ category.voices.length }}</text>
							</view>
						</scroll-view>
						
						<!-- 右侧音色列表 -->
						<scroll-view scroll-y class="voice-list">
							<view v-if="isLoadingVoices" class="loading">
								<uni-load-more status="loading" />
							</view>
							<template v-else>
								<view v-if="currentCategory && currentCategory.voices.length > 0">
									<view 
										v-for="voice in currentCategory.voices" 
										:key="voice.id"
										style="display: flex;justify-content: space-between;align-items: center;"
										class="voice-item"
										:class="{ 
											active: selectedVoice.id === voice.id,
											'need-vip': voice.needVip
										}"
										@tap="selectVoice(voice)"
									>
										<view>
											<view class="voice-info">
												<text class="voice-name">{{ voice.name }}</text>
												<text class="voice-tag" v-if="voice.tag">{{ voice.tag }}</text>
												<text class="voice-vip" v-if="voice.needVip && !isVip">VIP</text>
											</view>
											<text class="voice-desc">{{ voice.description }}</text>
										</view>
										
										<tts-icons type="bofang" @tap.stop="playAudio(voice.url)" size="50" color="#ddd" />
										
									</view>
								</view>
								<view v-else class="empty-state">
									<text class="empty-icon">🔍</text>
									<text class="empty-text">未找到相关音色</text>
								</view>
							</template>
						</scroll-view>
					</view>
				</view>
			</view>
		</view>

		<!-- 语速选择弹窗 -->
		<view v-if="showSpeedModalFlag" class="modal-overlay" @tap="closeSpeedModal">
			<view class="voice-modal" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">选择语速</text>
					<text class="close-btn" @tap="closeSpeedModal">×</text>
				</view>
				<view class="voice-content">
					<scroll-view scroll-y class="voice-list">
						<view 
							v-for="speed in speedOptions" 
							:key="speed.value"
							class="voice-item"
							:class="{ active: selectedSpeed === speed.value }"
							@tap="selectSpeed(speed)"
						>
							<view class="voice-info">
								<text class="voice-name">{{ speed.label }}</text>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>

		<!-- 情感强调选择弹窗 -->
		<view v-if="showEmotionModalFlag" class="modal-overlay" @tap="closeEmotionModal">
			<view class="voice-modal" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">选择情感强调</text>
					<text class="close-btn" @tap="closeEmotionModal">×</text>
				</view>
				<view class="voice-content">
					<scroll-view scroll-y class="voice-list">
						<view 
							v-for="emotion in emotionOptions" 
							:key="emotion.value"
							class="voice-item"
							:class="{ active: selectedEmotion === emotion.value }"
							@tap="selectEmotion(emotion)"
						>
							<view class="voice-info">
								<text class="voice-name">{{ emotion.label }}</text>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>

		<!-- 样例弹窗 -->
		<view v-if="showSampleModalFlag" class="modal-overlay" @tap="closeSampleModal">
			<view class="voice-modal" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">配音样例</text>
					<text class="close-btn" @tap="closeSampleModal">×</text>
				</view>
				<view class="voice-content">
					<scroll-view scroll-y class="voice-list">
						<view 
							v-for="sample in sampleTexts" 
							:key="sample.id"
							class="voice-item"
							@tap="useSample(sample)"
						>
							<view class="voice-info">
								<text class="voice-name">{{ sample.title }}</text>
							</view>
							<text class="voice-desc">{{ sample.text }}</text>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>

		<!-- 进度显示弹框 -->
		<view class="progress-mask" v-if="showProgress">
			<view class="progress-content">
				<view class="progress-header">
					<text class="progress-title">音频生成进度</text>
					<tts-icons type="guanbi" @tap="closeProgress" size="30" color="#999" />
				</view>
				<view class="progress-body">
					<view style="margin-bottom: 10rpx;">进度: {{ currentParagraph }}/{{ totalParagraphs }}</view>
					<view class="progress-bar">
						<view class="progress-inner" :style="{ width: paragraphProgress + '%' }"></view>
					</view>
					<view style="margin-bottom: 10rpx;">细节: {{ currentSentence }}/{{ totalSentences }}</view>
					<view class="progress-bar">
						<view class="progress-inner" :style="{ width: sentenceProgress + '%' }"></view>
					</view>
					<!-- <view class="progress-bar">
						<view class="progress-inner" :style="{ width: progress + '%' }"></view>
					</view>
					<text class="progress-text">{{ progress }}%</text> -->
					<!-- <view class="progress-details">
						<text class="progress-detail">段落: {{ currentParagraph }}/{{ totalParagraphs }}</text>
						<text class="progress-detail">句子: {{ currentSentence }}/{{ totalSentences }}</text>
					</view> -->
					<text class="progress-status">{{ statusMessage }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { voiceTypes, speedOptions, emotionOptions, synthesizeSpeech, ttsState, getVoiceList, synthesizeWithKokoroApi } from '@/services/tts'
import { userState, VIP_LEVELS, AD_CONFIG } from '@/services/user'
import VipModal from '@/components/vip-modal.vue'
import config from '@/config'
import { sendCustomerServiceMessage } from '@/services/auth'
import store from '@/store/index'



const inputText = ref('')
const selectedVoice = ref(voiceTypes[0])
const selectedSpeed = ref(0)
const selectedEmotion = ref(1)
const showVipModalFlag = ref(false)
const showVoiceModalFlag = ref(false)
const showSpeedModalFlag = ref(false)
const showEmotionModalFlag = ref(false)
const showSampleModalFlag = ref(false)
const isPlaying = ref(false)
const currentAudioContext = ref(null)
const inputMode = ref('import') // 'import' 或 'paste'
const voiceCategories = ref([])
const isLoadingVoices = ref(false)
const currentCategoryIndex = ref(0)
const isVip = ref(false)
const showProgress = ref(false)
const progress = ref(0)
const statusMessage = ref('')
const socket = ref(null)
const currentParagraph = ref(0)
const totalParagraphs = ref(0)
const currentSentence = ref(0)
const totalSentences = ref(0)
const ws = ref(null)
const paragraphProgress = ref(0)
const sentenceProgress = ref(0)
const currentAudioId = ref(null)


const configData = computed(() => store.state.config.config)
const userInfo = computed(() => store.state.user.userInfo)

// 计算属性
const currentCategory = computed(() => {
	if (voiceCategories.value.length === 0) return null
	return voiceCategories.value[currentCategoryIndex.value]
})

const showAd = computed(() => VIP_LEVELS[userState.value.vipLevel].hasAds)
const speedLabel = computed(() => speedOptions.find(o => o.value === selectedSpeed.value)?.label || '正常语速')
const emotionLabel = computed(() => emotionOptions.find(o => o.value === selectedEmotion.value)?.label || '正常情感')

// 从ttsState导入状态
const isConverting = computed(() => ttsState.value.isConverting)
const audioUrl = computed(() => ttsState.value.audioUrl)

// 发送消息
function sendMessage() {
	sendCustomerServiceMessage({
		content: '你好，我想咨询一下配音服务'
	})
}

// 配音历史
function gotoHistory() {
	uni.navigateTo({
		url: '/pages/history/index'
	})
}

// 获取声音列表
async function fetchVoiceList() {
	try {
		isLoadingVoices.value = true
		const categories = await getVoiceList()
		console.log({categories});
		
		voiceCategories.value = categories
		
		// 设置默认选中的声音
		if (categories.length > 0 && categories[0].voices.length > 0) {
			selectedVoice.value = categories[0].voices[0]
		}
	} catch (error) {
		console.error('获取声音列表失败:', error)
		uni.showToast({
			title: '获取声音列表失败',
			icon: 'none'
		})
	} finally {
		isLoadingVoices.value = false
	}
}

// 清除文字
function clearText() {
	inputText.value = ''
}

// 选择分类
function selectCategory(index) {
	currentCategoryIndex.value = index
}

// 播放音频
function playAudio(url) {
	try {
		// 如果已经在播放，先停止
		if (currentAudioContext.value) {
			stopAudio()
		}
		
		// 检查URL是否有效
		if (!url || typeof url !== 'string') {
			throw new Error('无效的音频URL')
		}
		
		console.log('开始播放音频:', url)
		
		// 先下载音频文件
		uni.showLoading({
			title: '加载音频中...',
			mask: true
		})
		
		uni.downloadFile({
			url: url,
			success: (res) => {
				uni.hideLoading()
				
				if (res.statusCode === 200) {
					console.log('音频下载成功:', res.tempFilePath)
					
					// 创建新的音频上下文
					currentAudioContext.value = uni.createInnerAudioContext()
					currentAudioContext.value.src = res.tempFilePath
					currentAudioContext.value.autoplay = true
					
					// 监听播放状态
					currentAudioContext.value.onPlay(() => {
						console.log('音频开始播放')
						isPlaying.value = true
					})
					
					currentAudioContext.value.onEnded(() => {
						console.log('音频播放结束')
						isPlaying.value = false
						currentAudioContext.value.destroy()
						currentAudioContext.value = null
					})
					
					currentAudioContext.value.onError((err) => {
						console.error('音频播放错误:', err)
						isPlaying.value = false
						currentAudioContext.value.destroy()
						currentAudioContext.value = null
						uni.showToast({
							title: '播放失败，请重试',
							icon: 'none'
						})
					})
					
					// 添加更多事件监听
					currentAudioContext.value.onCanplay(() => {
						console.log('音频可以播放')
					})
					
					currentAudioContext.value.onWaiting(() => {
						console.log('音频正在缓冲')
					})
					
					currentAudioContext.value.onTimeUpdate(() => {
						console.log('音频播放进度更新')
					})
				} else {
					throw new Error('音频下载失败')
				}
			},
			fail: (err) => {
				uni.hideLoading()
				console.error('音频下载失败:', err)
				uni.showToast({
					title: '音频加载失败，请重试',
					icon: 'none'
				})
			}
		})
	} catch (error) {
		uni.hideLoading()
		console.error('创建音频上下文失败:', error)
		uni.showToast({
			title: '播放失败，请重试',
			icon: 'none'
		})
	}
}

// 停止播放
function stopAudio() {
	if (currentAudioContext.value) {
		try {
			currentAudioContext.value.stop()
			currentAudioContext.value.destroy()
			currentAudioContext.value = null
			isPlaying.value = false
			console.log('音频已停止播放')
		} catch (error) {
			console.error('停止音频播放失败:', error)
		}
	}
}

// 处理播放/停止
function handlePlay() {
	console.log('点击播放按钮, 当前状态:', isPlaying.value, '音频URL:', audioUrl.value)
	if (isPlaying.value) {
		stopAudio()
	} else if (audioUrl.value) {
		// 确保URL是有效的
		if (audioUrl.value.startsWith('http')) {
			playAudio(audioUrl.value)
		} else {
			uni.showToast({
				title: '无效的音频地址',
				icon: 'none'
			})
		}
	} else {
		uni.showToast({
			title: '没有可播放的音频',
			icon: 'none'
		})
	}
}

// 使用Kokoro引擎合成语音
async function synthesizeWithKokoro(text, options) {
	// let progressInterval = null
	try {
		// const token = uni.getStorageSync('token')
		// if (!token) {
		// 	throw new Error('请先登录')
		// }
		
		// // 设置合成状态
		// ttsState.value.isConverting = true
		// ttsState.value.progress = 0
		
		
		
		// // 调用Kokoro引擎API
		// const result = await uni.request({
		// 	url: `${config.apiBaseUrl}/api/audio/kokoro/synthesize`,
		// 	method: 'POST',
		// 	timeout: 10000*5,
		// 	header: {
		// 		'Content-Type': 'application/json',
		// 		'Authorization': token
		// 	},
		// 	data: {
		// 		text: text,
		// 		voice: options.voiceType || 'zf_078',
		// 		speed: options.speed || 1.0,
		// 		lang_code: options.lang_code || 'z'
		// 	}
		// })

		const result = await synthesizeWithKokoroApi({
			text,
			voice: options.voiceType || 'zf_078',
			speed: options.speed || 1.0,
			lang_code: options.lang_code || 'z'
		})
		console.log({result})
		// if (result.statusCode !== 200 || result.data.code !== 200) {
		// 	throw new Error(result.data.message || '语音合成失败')
		// }
		
		// 更新合成状态
		// ttsState.value.progress = 100
		// ttsState.value.audioUrl = result.data.data.url
		// ttsState.value.isConverting = false
		
		return result
	} catch (error) {
		// 更新合成状态
		ttsState.value.isConverting = false
		closeProgress()
		throw error
	}
}

// 合成配音
async function handleConvert() {
	try {
		if (!inputText.value) {
			throw new Error('请输入要转换的文字')
		}
		
		// 检查VIP用户的字数限制
		if (!isVip.value && inputText.value.length > configData.value.free_user_limits.max_chars_per_request) {
			throw new Error(`免费用户每次配音不能超过${configData.value.free_user_limits.max_chars_per_request}字，开通VIP可享受${configData.value.vip_user_limits.max_chars_per_request}字数`)
		}
		
		let result = null
		// 根据声音的engine字段判断使用哪个合成接口
		if (selectedVoice.value.engine === 'kokoro') {
			// 适配语速
			const speedOptions = {
				'-100': 0.5,
				'-50': 0.75,
				'1':1,
				'+50': 1.5,
				'+100': 2
			}
			// 使用Kokoro引擎
			result = await synthesizeWithKokoro(inputText.value, {
				voiceType: selectedVoice.value.id,
				speed: speedOptions[selectedSpeed.value],
				lang_code: selectedVoice.value.lang_code
			})
			console.log('Kokoro合成结果:', result)
		} else {
			// 使用默认引擎
			result = await synthesizeSpeech(inputText.value, {
				voiceType: selectedVoice.value.id,
				speed: selectedSpeed.value,
				styleDegree: selectedEmotion.value
			})
			console.log('默认合成结果:', result)
			// if (result.code !== 200) {
			// 	throw new Error(result.message || '语音合成失败')
			// }
		}
		const data = result.data
		
		currentAudioId.value = data.id
		// 如果音频URL为空，则显示进度弹框，异步合成
		if (!data.url) {
			// 显示进度弹框
			showProgress.value = true
			return
		}
		
		// 更新音频URL
		ttsState.value.audioUrl = data.url
		console.log('设置音频URL:', data.url)
		
		// 合成成功后自动播放
		if (data.url) {
			// 延迟一下再播放，确保URL已经设置好
			setTimeout(() => {
				playAudio(data.url)
			}, 300)
		}

		uni.showToast({
			title: '合成成功',
			icon: 'success'
		})
	} catch (error) {
		console.error('合成失败:', error)
		closeProgress()
		uni.showToast({
			title: error.message,
			icon: 'none'
		})
	}
}

// 显示VIP弹窗
function showVipModal() {
	// showVipModalFlag.value = true
	// uni.navigateTo({
	// 	url: '/pages/vip/index'
	// })
	uni.showToast({
		title: '请联系客服，开通会员',
		icon: 'none'
	})
	return
}

// 购买会员
async function handleBuyVip(level) {
	try {
		// 模拟支付过程
		uni.showLoading({
			title: '正在开通...',
			mask: true
		})
		
		// 模拟网络请求延迟
		await new Promise(resolve => setTimeout(resolve, 1500))
		
		// 更新用户状态
		userState.value.vipLevel = level
		
		uni.hideLoading()
		uni.showToast({
			title: '开通成功',
			icon: 'success',
			duration: 2000
		})
		
		// 延迟关闭弹窗，让用户看到成功提示
		setTimeout(() => {
			showVipModalFlag.value = false
		}, 2000)
	} catch (error) {
		uni.hideLoading()
		uni.showToast({
			title: error.message || '开通失败，请重试',
			icon: 'none',
			duration: 2000
		})
	}
}

// 显示音色选择弹窗
function showVoiceModal() {
	showVoiceModalFlag.value = true
}

// 关闭音色选择弹窗
function closeVoiceModal() {
	showVoiceModalFlag.value = false
}

// 选择音色
function selectVoice(voice) {
	if (voice.needVip && !isVip.value) {
		closeVoiceModal()
		showVipModal()
		return
	}
	selectedVoice.value = voice
	closeVoiceModal()
}

// 显示语速选择弹窗
function showSpeedModal() {
	showSpeedModalFlag.value = true
}

// 关闭语速选择弹窗
function closeSpeedModal() {
	showSpeedModalFlag.value = false
}

// 选择语速
function selectSpeed(speed) {
	selectedSpeed.value = speed.value
	closeSpeedModal()
}

// 显示情感强调选择弹窗
function showEmotionModal() {
	showEmotionModalFlag.value = true
}

// 关闭情感强调选择弹窗
function closeEmotionModal() {
	showEmotionModalFlag.value = false
}

// 选择情感强调
function selectEmotion(emotion) {
	selectedEmotion.value = emotion.value
	closeEmotionModal()
}

// 显示样例弹窗
function showSampleModal() {
	showSampleModalFlag.value = true
}

// 关闭样例弹窗
function closeSampleModal() {
	showSampleModalFlag.value = false
}

// 使用样例
async function useSample(sample) {
	try {
		// 设置输入文本
		inputText.value = sample.text
		
		// 设置音色
		const voice = voiceTypes.find(v => v.id === sample.voice)
		if (voice) {
			if (voice.needVip && !isVip.value) {
				closeSampleModal()
				showVipModal()
				return
			}
			selectedVoice.value = voice
		}
		
		// 设置语速
		selectedSpeed.value = sample.speed
		
		// 设置情感
		selectedEmotion.value = sample.emotion
		
		// 关闭弹窗
		closeSampleModal()
		
		// 自动开始合成
		// await handleConvert()
	} catch (error) {
		uni.showToast({
			title: error.message || '使用样例失败',
			icon: 'none'
		})
	}
}

// 导出配音
async function handleExport() {
	try {
		if (!audioUrl.value) {
			throw new Error('请先合成配音')
		}

		// 跳转到导出页面
		uni.navigateTo({
			url: `/pages/export/export?url=${encodeURIComponent(audioUrl.value)}`
		})
	} catch (error) {
		if (error.message === '导出功能需要开通会员') {
			showVipModal()
		} else {
			uni.showToast({
				title: error.message,
				icon: 'none'
			})
		}
	}
}

// 获取会员信息
async function fetchVipInfo() {
	try {
		const token = uni.getStorageSync('token')
		if (!token) {
			return
		}
		
		const result = await uni.request({
			url: `${config.apiBaseUrl}/api/vip/info`,
			method: 'GET',
			header: {
				'Authorization': token
			}
		})
		
		if (result.statusCode !== 200 || result.data.code !== 200) {
			throw new Error(result.data.message || '获取会员信息失败')
		}
		
		// 更新VIP信息
		let vipInfo  = result.data.data
		
		// 更新用户状态中的VIP信息
		// if (userState.value) {
		// 	userState.value.vipLevel = vipInfo.value.is_vip ? 'VIP' : 'FREE'
		// }
		isVip.value = vipInfo.is_vip
		userState.value.vipLevel = vipInfo.is_vip ? 'VIP' : 'FREE'
	} catch (error) {
		console.error('获取会员信息失败:', error)
	}
}

// 页面加载时获取会员信息和声音列表
onMounted(() => {
	fetchVipInfo()
	fetchVoiceList()
	initWebSocket()
})

// 配音样例数据
const sampleTexts = [
	{
		id: 1,
		title: '产品介绍',
		text: '欢迎使用我们的智能配音系统。本系统采用先进的AI技术，为您提供自然流畅的语音合成服务。无论是商业广告、教育培训，还是个人创作，都能满足您的需求。',
		voice: 'xiaoyi',
		speed: 0,
		emotion: 1
	},
	{
		id: 2,
		title: '情感表达',
		text: '今天是个特别的日子，阳光明媚，微风轻拂。我们相聚在这里，共同见证这美好的时刻。感谢一路相伴，愿我们继续携手前行，创造更多精彩。',
		voice: 'xiaomei',
		speed: 0,
		emotion: 2
	},
	{
		id: 3,
		title: '广告文案',
		text: '限时特惠，全场商品低至5折！精选好物，品质保证，让您享受超值购物体验。错过今天，再等一年，赶快行动起来吧！',
		voice: 'xiaogang',
		speed: 1,
		emotion: 3
	}
]

// 切换输入模式
function switchInputMode(mode) {
	inputMode.value = mode
	if (mode === 'paste') {
		// 切换到粘贴模式时，自动获取剪贴板内容
		getClipboardContent()
	}
}

// 获取剪贴板内容
function getClipboardContent() {
	uni.getClipboardData({
		success: (res) => {
			if (res.data) {
				inputText.value = res.data
				uni.showToast({
					title: '已粘贴剪贴板内容',
					icon: 'success'
				})
			} else {
				uni.showToast({
					title: '剪贴板为空',
					icon: 'none'
				})
			}
		},
		fail: () => {
			uni.showToast({
				title: '获取剪贴板失败',
				icon: 'none'
			})
		}
	})
}

// 初始化WebSocket连接
const initWebSocket = () => {
	if (ws.value) {
		ws.value.close()
	}
	
	// 使用uni.connectSocket连接WebSocket
	ws.value = uni.connectSocket({
		url: `wss://crmeb.tietaozhe.com/ws`,
		header: {
			'content-type': 'application/json'
		},
		method: 'GET',
		success: (res) => {
			console.log('WebSocket连接成功:', res)
			statusMessage.value = '正在连接...'
		}
	})
	
	// 监听WebSocket连接打开
	ws.value.onOpen((res) => {
		console.log('WebSocket连接已建立')
		statusMessage.value = '正在连接...'
	})
	
	// 监听WebSocket消息
	ws.value.onMessage((res) => {
		if(!res) return
		const data = JSON.parse(res.data)
		switch(data.type) {
			case 'init':
				// 初始化,绑定用户uid
				ws.value.send({
					data:JSON.stringify({
						type: 'bindUid',
						uid: userInfo.value.user_info.id
					})
				})
				break
			case 'progress':
				if(currentAudioId.value !== data.audio_id) return
				if(data.status === 'processing') {
					// 更新进度信息
					currentParagraph.value = Math.floor(data.current_paragraph)
					totalParagraphs.value = data.total_paragraphs
					currentSentence.value = data.current_sentence
					totalSentences.value = data.total_sentences
					statusMessage.value = data.message
					
					// 计算总体进度
					paragraphProgress.value = Math.round((data.current_paragraph / data.total_paragraphs) * 100)
					sentenceProgress.value = Math.round((data.current_sentence / data.total_sentences) * 100)
					
				}else if(data.status === 'adding') {
					// 合并音频
					statusMessage.value = data.message
				}else if(data.status === 'completed') {
					// 合成成功
					ttsState.value.audioUrl = data.url
					statusMessage.value = data.message
					closeProgress()
					setTimeout(() => {
						playAudio(data.url)
					}, 300)
				}
				
				break
			case 'error':
				if(currentAudioId.value !== data.audio_id) return
				statusMessage.value = '错误: ' + data.message
				uni.showToast({
					title: data.message,
					icon: 'none'
				})
				closeProgress()
				break
			case 'warning':
				if(currentAudioId.value !== data.audio_id) return
				statusMessage.value = '警告: ' + data.message
				break
		}
	})
	
	// 监听WebSocket错误
	ws.value.onError((error) => {
		console.error("WebSocket错误:", error)
		statusMessage.value = '连接错误，请重试'
		uni.showToast({
			title: '连接错误，请重试',
			icon: 'none'
		})
		closeProgress()
	})
	
	// 监听WebSocket关闭
	ws.value.onClose((res) => {
		console.log("WebSocket连接已关闭")
		if (progress.value < 100) {
			statusMessage.value = '连接已断开，请重试'
		} else {
			closeProgress()
		}
	})
}

// 关闭进度弹框
const closeProgress = () => {
	// ws.value.close()
	showProgress.value = false
	progress.value = 0
	statusMessage.value = ''
	currentParagraph.value = 0
	totalParagraphs.value = 0
	currentSentence.value = 0
	totalSentences.value = 0
	paragraphProgress.value = 0
	sentenceProgress.value = 0
}

// 组件卸载时关闭WebSocket
onUnmounted(() => {
	if (currentAudioContext.value) {
		currentAudioContext.value.destroy()
	}
	ws.value.close()
})
</script>

<style lang="scss">
.container {
	padding: 20rpx;
	padding-bottom: 180rpx;
	background: #f8f8f8;
	min-height: 100vh;
}

.vip-banner {
	background: linear-gradient(to right, #ffd700, #ffa500);
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.vip-info {
	.vip-title {
		font-size: 32rpx;
		color: #fff;
		font-weight: bold;
		margin-bottom: 10rpx;
		display: block;
	}
	
	.vip-desc {
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.8);
	}
}

.vip-btn {
	background: #fff;
	color: #ffa500;
	font-size: 28rpx;
	padding: 10rpx 30rpx;
	border-radius: 30rpx;
}

.input-area {
	background: #fff;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.input-header {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.input-tab {
	font-size: 28rpx;
	color: #666;
	margin-right: 30rpx;
	padding: 10rpx;
	
	&.active {
		color: #35ae91;
		font-weight: bold;
	}
	
	&:active {
		opacity: 0.8;
	}
}

.hot-sample {
	font-size: 26rpx;
	color: #ff6b6b;
	margin-left: auto;
	padding: 10rpx;
	
	&:active {
		opacity: 0.8;
	}
}

.input-content {
	width: 100%;
	height: 300rpx;
	font-size: 28rpx;
	line-height: 1.6;
}

.word-count {
	text-align: right;
	font-size: 24rpx;
	color: #999;
	margin: 10rpx 0;
}

.tool-buttons {
	display: flex;
	gap: 20rpx;
}

.tool-btn {
	flex: 1;
	font-size: 26rpx;
	color: #666;
	background: #f5f5f5;
	border: none;
	border-radius: 8rpx;
	padding: 15rpx 0;
}

.voice-settings {
	background: #fff;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.setting-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 0;
	border-bottom: 1px solid #f5f5f5;

	&:last-child {
		border-bottom: none;
	}
}

.setting-label {
	display: flex;
	align-items: center;
	gap: 10rpx;
	font-size: 28rpx;
	color: #333;
}

.setting-value {
	flex: 1;
	text-align: right;
	font-size: 28rpx;
	color: #666;
	margin-right: 10rpx;

	.tag {
		display: inline-block;
		font-size: 24rpx;
		color: #ff6b6b;
		background: #fff5f5;
		padding: 4rpx 12rpx;
		border-radius: 6rpx;
		margin-left: 10rpx;
	}
}

.arrow {
	color: #999;
	font-size: 24rpx;
}

.ad-container {
	margin: 20rpx 0;
}

.bottom-buttons {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	gap: 20rpx;
	padding: 20rpx;
	background: #fff;
}

.primary-btn {
	flex: 1;
	background: #35ae91;
	color: #fff;
	border: none;
	border-radius: 8rpx;
	padding: 20rpx 0;
	font-size: 30rpx;
}

.secondary-btn {
	flex: 1;
	background: #fff;
	color: #35ae91;
	border: 1px solid #35ae91;
	border-radius: 8rpx;
	padding: 20rpx 0;
	font-size: 30rpx;
	
	&[disabled] {
		color: #999;
		border-color: #999;
	}
}

.play-btn {
	flex: 1;
	background: #ff6b6b;
	color: #fff;
	border: none;
	border-radius: 8rpx;
	padding: 20rpx 0;
	font-size: 30rpx;
	
	&:active {
		opacity: 0.9;
	}
}

/* 弹窗样式 */
.modal-overlay {
	position: fixed;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 999;
	display: flex;
	flex-direction: column;
	justify-content: flex-end;
	animation: fadeIn 0.3s ease-out;
}

.voice-modal {
	position: relative;
	width: 100%;
	background: #ffffff;
	border-radius: 24rpx 24rpx 0 0;
	overflow: hidden;
	max-height: 90vh;
	transform: translateY(0);
	animation: slideUp 0.3s ease-out;
	
	.modal-header {
		position: relative;
		padding: 30rpx;
		text-align: center;
		border-bottom: 1rpx solid #f5f5f5;
		background: #fff;
		
		&::after {
			content: '';
			position: absolute;
			left: 50%;
			top: 12rpx;
			transform: translateX(-50%);
			width: 60rpx;
			height: 6rpx;
			background: #e5e5e5;
			border-radius: 3rpx;
		}
		
		.modal-title {
			font-size: 32rpx;
			font-weight: 600;
			color: #333;
		}
		
		.close-btn {
			position: absolute;
			right: 30rpx;
			top: 50%;
			transform: translateY(-50%);
			font-size: 40rpx;
			color: #999;
			padding: 10rpx;
		}
	}
	
	.voice-content {
		padding: 30rpx;
		max-height: calc(90vh - 90rpx);
		overflow-y: auto;
		-webkit-overflow-scrolling: touch;
		
		.category-container {
			display: flex;
			height: 70vh;
			background: #fff;
			border-radius: 16rpx;
			overflow: hidden;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
		}
		
		.category-list {
			width: 220rpx;
			background-color: #f8f8f8;
			height: 100%;
			border-right: 1rpx solid #eee;
			
			.category-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 30rpx 20rpx;
				border-bottom: 1rpx solid #eee;
				position: relative;
				transition: all 0.3s ease;
				
				&.active {
					background-color: #fff;
					
					&::before {
						content: '';
						position: absolute;
						left: 0;
						top: 50%;
						transform: translateY(-50%);
						width: 8rpx;
						height: 40rpx;
						background-color: #07c160;
						border-radius: 0 4rpx 4rpx 0;
					}
					
					.category-name {
						color: #07c160;
						font-weight: bold;
					}
				}
				
				.category-name {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 10rpx;
					transition: all 0.3s ease;
				}
				
				.category-count {
					font-size: 22rpx;
					color: #999;
					background-color: #eee;
					padding: 4rpx 12rpx;
					border-radius: 20rpx;
				}
				
				&:active {
					opacity: 0.8;
				}
			}
		}
		
		.voice-list {
			flex: 1;
			background-color: #fff;
			height: 100%;
			padding: 0 20rpx;
			
			.loading {
				padding: 40rpx 0;
				text-align: center;
			}
			
			.voice-item {
				padding: 24rpx;
				border-radius: 16rpx;
				background: #f8f8f8;
				margin-bottom: 20rpx;
				transition: all 0.3s ease;
				border: 1rpx solid transparent;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				&.active {
					background: #fff;
					border: 2rpx solid #07c160;
					box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.1);
					
					.voice-name {
						color: #07c160;
					}
				}
				
				&.need-vip {
					opacity: 0.7;
					position: relative;
					
					&::after {
						content: 'VIP';
						position: absolute;
						top: 10rpx;
						right: 10rpx;
						font-size: 20rpx;
						color: #fff;
						background: linear-gradient(45deg, #ffd700, #ffa500);
						padding: 4rpx 12rpx;
						border-radius: 20rpx;
					}
				}
				
				.voice-info {
					display: flex;
					align-items: center;
					margin-bottom: 12rpx;
					
					.voice-name {
						font-size: 28rpx;
						font-weight: 600;
						color: #333;
						margin-right: 12rpx;
						transition: all 0.3s ease;
					}
					
					.voice-tag {
						font-size: 20rpx;
						color: #fff;
						background: #ff6b6b;
						padding: 4rpx 12rpx;
						border-radius: 20rpx;
						margin-right: 8rpx;
					}
					
					.voice-vip {
						font-size: 20rpx;
						color: #ffd700;
						background: #fff5e6;
						padding: 4rpx 12rpx;
						border-radius: 20rpx;
					}
				}
				
				.voice-desc {
					font-size: 24rpx;
					color: #666;
					line-height: 1.4;
				}
				
				&:active {
					transform: scale(0.98);
				}
			}
			
			.empty-state {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 100rpx 0;
				
				.empty-icon {
					font-size: 80rpx;
					color: #ddd;
					margin-bottom: 20rpx;
				}
				
				.empty-text {
					font-size: 28rpx;
					color: #999;
				}
			}
		}
	}
}

@keyframes fadeIn {
	from {
		background: rgba(0, 0, 0, 0);
	}
	to {
		background: rgba(0, 0, 0, 0.5);
	}
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}
	to {
		transform: translateY(0);
	}
}
.customer-service-btn {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 100rpx;
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  line-height: 1;
  .feature-list-item-content {
    display: flex;
    align-items: center;
  }
  &::after {
    border: none;
  }
  
  &:active {
    opacity: 0.8;
  }
}

.progress-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.6);
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
	
	.progress-content {
		width: 600rpx;
		background: #fff;
		border-radius: 24rpx;
		padding: 40rpx;
		
		.progress-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;
			
			.progress-title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}
		}
		
		.progress-body {
			.progress-bar {
				height: 20rpx;
				background: #f0f0f0;
				border-radius: 10rpx;
				overflow: hidden;
				margin-bottom: 20rpx;
				
				.progress-inner {
					height: 100%;
					background: #07c160;
					transition: width 0.3s ease;
				}
			}
			
			.progress-details {
				display: flex;
				flex-direction: column;
				gap: 10rpx;
				margin-bottom: 20rpx;
				
				.progress-detail {
					font-size: 26rpx;
					color: #666;
					text-align: center;
				}
			}
			
			.progress-text {
				display: block;
				text-align: center;
				font-size: 32rpx;
				color: #07c160;
				margin-bottom: 20rpx;
			}
			
			.progress-status {
				display: block;
				text-align: center;
				font-size: 28rpx;
				color: #666;
			}
		}
	}
}
</style>
